/*
 * 文 件 名:  ProductServiceProviderImpl.java
 * 创建日期:  2012-9-17
 * 版    权:  Epro Technologies Co., Ltd. Copyright 2011-2012,  All rights reserved
 * 作    者:  hjd008
 */
package com.weipu.common.facade.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.location.Geocoder;
import android.text.TextUtils;
import android.util.Log;

import com.weipu.common.constants.Constant;
import com.weipu.common.constants.Constant.HttpMethod;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.ProductServiceProvider;
import com.weipu.common.facade.content.api.ProductService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.model.AllCatelogModel;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.CustomerPhotosModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.facade.model.ProductResultModel;
import com.weipu.common.facade.model.ReviewlistModel;
import com.weipu.common.facade.model.SalesLimitModel;
import com.weipu.common.facade.model.SearchModel;
import com.weipu.common.facade.support.service.TaskExecutor;
import com.weipu.common.facade.support.service.task.BaseServiceTask;
import com.weipu.common.facade.support.service.task.GetChildCategoriesTask;
import com.weipu.common.facade.support.service.task.GetProductListByCategoryIdAndRelatedTypeTask;
import com.weipu.common.okhttp.UrlUtils;
import com.weipu.common.util.CacheUtil;
import com.weipu.common.util.GlobalConfig;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

import static android.R.attr.type;

/**
 * 商品服务提供者实现类
 *
 * @author hjd008
 * @version [版本号, 2012-9-29]
 * @history us仓版本更新，详情见Line:1312
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

public class ProductServiceProviderImpl extends BaseServiceProviderImpl
        implements ProductServiceProvider {

    private static Map<String, String> mapUrl;

    private static Map<String, HttpMethod> mapMethod;

    /**
     * 一级栏目默认父目录ID
     */
    public static final String TOP_CATEGORY_DEFAULT_PARENT_ID = "-1";

    public ProductServiceProviderImpl() {
        productService = new ProductService();
    }

    // 初始化方法名和url键和值存放
    static {
        mapUrl = new HashMap<String, String>();
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES,
                Constant.GETTOPCATEGORIES_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETCHILDCATEGORIES,
                Constant.GETCHILDCATEGORIES_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETALLCHILDCATEGORIES,
                Constant.GETALLCHILDCATEGORIES_URL);


		mapUrl.put(
				ServerConstant.RequestMethodNameConstant.METHOD_LATESTDISCOUNTS,
				Constant.LATESTDISCOUNTS_URL);
        //TODO US仓版本修改 地址需要动态获取
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_USWAREHOUSE,
                Constant.USWAREHOUSE_URL);

        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_MVPRODUCTS,
                Constant.MVPRODUCTS_URL);
        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_NEWARRIVALS,
                Constant.NEWARRIVALS_URL);
        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_TOPSELLERS,
                Constant.TOPSELLERS_URL);
        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_SPOTLIGHTS,
                Constant.SPOTLIGHTS_URL);

        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETSEARCHPRODUCTLIST,
                Constant.GETSEARCHPRODUCTLIST_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTUP,
                Constant.GETPRODUCTLISTUP_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLIST,
                Constant.GETPRODUCTLIST_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTBYCATEGORYID,
                Constant.GETPRODUCTLISTBYCATEGORYID_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTBYCATEGORYIDANDRELATEDTYPE,
                Constant.GETPRODUCTLISTBYCATEGORYIDANDRELATEDTYPE_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTRESULTBYCATEGORYRELATEDTYPE,
                Constant.GETPRODUCTRESULTBYCATEGORYRELATEDTYPE_URL);
        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTRESULT,
                Constant.GETPRODUCTRESULT_URL);

        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_CUSOTMERPHOTOLIST,
                Constant.CUSOTMERPHOTOLIST_URL);

        mapUrl.put(
                ServerConstant.RequestMethodNameConstant.METHOD_CUSOTMERREVIEWLIST,
                Constant.CUSOTMERREVIEWLIST_URL);

        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCT,
                Constant.GETPRODUCTDETAIL_URL);
        // 库存量URL
        mapUrl.put(ServerConstant.RequestMethodNameConstant.METHOD_SALESLIMIT,
                Constant.SALESLIMIT_URL);

    }

    // 初始化方法名和httpmetod键和值存放
    static {
        mapMethod = new HashMap<String, HttpMethod>();
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETCHILDCATEGORIES,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETALLCHILDCATEGORIES,
                        HttpMethod.GET);

        //US仓版本修改 修改为USWAREHOUSE
        mapMethod.put(ServerConstant.RequestMethodNameConstant.METHOD_USWAREHOUSE,
                HttpMethod.GET);
		mapMethod
				.put(ServerConstant.RequestMethodNameConstant.METHOD_LATESTDISCOUNTS,
						HttpMethod.GET);
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_MVPRODUCTS,
                HttpMethod.GET);
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_NEWARRIVALS,
                HttpMethod.GET);
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_TOPSELLERS,
                HttpMethod.GET);
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_SPOTLIGHTS,
                HttpMethod.GET);

        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETCOUNTWISHLISTFORUSER,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_WISHLISTINFOFORUSER,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_ADDWISHLISTFORUSER,
                        HttpMethod.POST);

        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETSEARCHPRODUCTLIST,
                        HttpMethod.GET);
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLIST,
                HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTUP,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTBYCATEGORYID,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTLISTBYCATEGORYIDANDRELATEDTYPE,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTRESULTBYCATEGORYRELATEDTYPE,
                        HttpMethod.GET);
        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCTRESULT,
                        HttpMethod.GET);

        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_CUSOTMERPHOTOLIST,
                        HttpMethod.GET);

        mapMethod
                .put(ServerConstant.RequestMethodNameConstant.METHOD_CUSOTMERREVIEWLIST,
                        HttpMethod.GET);

        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_GETPRODUCT,
                HttpMethod.GET);
        // 库存量
        mapMethod.put(
                ServerConstant.RequestMethodNameConstant.METHOD_SALESLIMIT,
                HttpMethod.POST);

    }

    // /**
    // *
    // * 调用服务端接口put和post的封装方法
    // *
    // * @param methodName
    // * @param map
    // * @return 调用的接口的方法名，map存放的参数
    // * @return String [返回类型说明]
    // * @exception throws [违例类型] [违例说明]
    // * @see [类、类#方法、类#成员]
    // */
    // JSONObject postOrPutWebInterface(String methodName, Object object)
    // throws DxException
    // {
    // String result = null;
    // JSONObject json = null;
    // postOrPutAuthenticationAndsetHeadAndmessage(object);
    // try
    // {
    // ResponseEntity<String> response =
    // restTemplate.exchange(mapUrl.get(methodName), mapMethod.get(methodName),
    // requestEntity, String.class);
    // result = response.getBody().toString();
    // Logger.i("postOrPutWebInterface", result);
    // json = returnResult(result);
    // }
    // catch (HttpClientErrorException e)
    // {
    // throw new DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
    // }
    // catch (ResourceAccessException e)
    // {
    // Logger.e(e.getMessage(), e);
    // // 链接超时
    // if (e.getCause() instanceof SocketTimeoutException||e.getCause()
    // instanceof ConnectTimeoutException)
    // {
    // throw new
    // DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT);
    // }
    // else if(e.getCause() instanceof UnknownHostException){
    // throw new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
    // }
    // else
    // {
    // if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){
    // throw new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
    // }else{
    // throw new DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
    // }
    // }
    // }catch(HttpServerErrorException e){
    // throw new DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR);
    // }
    // return json;
    // }

    // 栏目本地数据操作实体对象
    // private CategoryService categoryService;

    // 产品本地数据操作实体对象
    private ProductService productService;

    private static final String TAG = ProductServiceProviderImpl.class
            .getSimpleName();

    /**
     * 获取顶级目录列表[参数说明]
     * <p>
     * 按照三级数据缓存依次读取，如果数据存在则直接返回并更新高级别缓存，读取优先级如下：
     * <p>
     * 1、内存读取 2、本地数据库读取 3、远程服务端读取
     * <p>
     * 注：缓存策略见{@link CacheUtil}
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public ArrayList<CatelogModel> getTopCategories(boolean isLoadFromCache, long customerID, boolean isFilter, String categoryIds)
            throws DxException {
        /*
		 * // 【本地内存读取】 if (isLoadFromCache && null !=
		 * GlobalConfig.getInstance().
		 * getSubCategoryList().get(TOP_CATEGORY_DEFAULT_PARENT_ID)) { return
		 * new ArrayList<CatelogModel>(GlobalConfig.getInstance()
		 * .getSubCategoryList()
		 * .get(TOP_CATEGORY_DEFAULT_PARENT_ID));//缓存数据需要与UI数据隔离
		 * ，防止两边修改(clear、remove)造成影响 }
		 * 
		 * // 【从本地数据库获取】 if (isLoadFromCache) { ArrayList<CatelogModel>
		 * topCategroyList =
		 * categoryService.queryCategoryListByParentCategoryID(
		 * TOP_CATEGORY_DEFAULT_PARENT_ID); // 一级目录数据为不为空，直接返回 if (null !=
		 * topCategroyList && !topCategroyList.isEmpty()) { // 刷新内存缓存
		 * GlobalConfig
		 * .getInstance().getSubCategoryList().put(TOP_CATEGORY_DEFAULT_PARENT_ID
		 * , topCategroyList); return new
		 * ArrayList<CatelogModel>(topCategroyList
		 * );//缓存数据需要与UI数据隔离，防止两边修改(clear、remove)造成影响 } // //清理本地失效缓存数据 // int
		 * topCacheCount = categoryService.deleteCategoryListByParentID(
		 * TOP_CATEGORY_DEFAULT_PARENT_ID); // Logger.i(TAG,
		 * "Clear top category list, size: " + topCacheCount); }
		 */

        // 【服务端读取】
        // 查询服务端一级栏目数据并保存到数据库中
        ArrayList<CatelogModel> listCatelogModel = null;
        JSONObject jsonData = requestHttpGetData(Constant.GETTOPCATEGORIES_URL + "?CustomerID=" + customerID + "&IsFilter=" + isFilter + "&CategoryIds=" + categoryIds
        );
        JSONArray jsonArray = jsonData
                .optJSONArray(ServerConstant.Catelog.CONSTANT_MODEL);
        if (jsonArray != null) {
            listCatelogModel = new ArrayList<CatelogModel>();
            CatelogModel tmpModel = null;

            for (int i = 0; i < jsonArray.length(); i++) {
                tmpModel = CatelogModel.json2TopCategories(jsonArray
                        .optJSONObject(i));
                tmpModel.setCacheUpdateTime(System.currentTimeMillis());// 刷新更新时间
                // 刷新本地数据库缓存
                // if (isLoadFromCache)
                // {
                // categoryService.saveCategoryInfo(tmpModel);// 保存到本地数据库里面
                // }
                tmpModel.setParentId(TOP_CATEGORY_DEFAULT_PARENT_ID);// 设置默认父栏目ID
                listCatelogModel.add(tmpModel);

            }
        }

        // 刷新内存缓存
        // if (isLoadFromCache && null != listCatelogModel &&
        // !listCatelogModel.isEmpty())
        // {
        // GlobalConfig.getInstance()
        // .getSubCategoryList()
        // .put(TOP_CATEGORY_DEFAULT_PARENT_ID, new
        // ArrayList<CatelogModel>(listCatelogModel));//使用新列表数据存储，防止UI
        // 对列表Clear、remove操作
        // }
        return listCatelogModel;

    }

    /**
     * 获取顶级目录列表[参数说明]
     * <p>
     * 按照三级数据缓存依次读取，如果数据存在则直接返回并更新高级别缓存，读取优先级如下：
     * <p>
     * 1、内存读取 2、本地数据库读取 3、远程服务端读取
     * <p>
     * 注：缓存策略见{@link CacheUtil}
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public ArrayList<CatelogModel> getTopCategories(long customerID, boolean isFilter, String categoryIds) throws DxException {
        return getTopCategories(true, customerID, isFilter, categoryIds);
    }

    /**
     * 获取父目录下所有的目录列表[参数说明]
     *
     * @param categoryId 目录ID
     * @return categoryId [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public ArrayList<AllCatelogModel> getAllChildCategories(int categoryId)
            throws DxException {
        return getAllChildCategories(categoryId, false);
    }

    /**
     * 获取父目录下所有的目录列表[参数说明]
     *
     * @param categoryId      目录ID
     * @param isLoadFromCache 是否从缓存读取
     * @return categoryId [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public ArrayList<AllCatelogModel> getAllChildCategories(int categoryId,
                                                            boolean isLoadFromCache) throws DxException {
        // //栏目内存缓存
        // if (isLoadFromCache
        // && CacheUtil.getInstance().isEnableCategoryMemCache())
        // {
        // Logger.i(TAG,
        // "GetChildCategories.memory.chache: Loading from memory.");
        //
        // //获取内存缓存数据
        // ArrayList<AllCatelogModel> memoryCacheList =
        // GlobalConfig.getInstance()
        // .getSubCategoryList()
        // .get(String.valueOf(categoryId));
        //
        // //缓存数据不为空
        // if (null != memoryCacheList && !memoryCacheList.isEmpty())
        // {
        // boolean isCacheHit = CacheUtil.getInstance()
        // .isCategoryModelHitCache(memoryCacheList.get(0));
        //
        // Logger.i(TAG,
        // "GetChildCategories.memory.chache: Loading from memory, return: "
        // + memoryCacheList.size());
        //
        // //缓存数据有效立即返回
        // if (isCacheHit)
        // {
        // Logger.i(TAG,
        // "GetChildCategories.memory.chache: return from memory success.");
        //
        // // 判定是否需要预加载刷新缓存
        // if (CacheUtil.getInstance()
        // .isNeedRefreshCache(memoryCacheList.get(0)))
        // {
        // //异步刷新缓存
        // flushGetChildCategories(categoryId);
        // }
        // return new ArrayList<CatelogModel>(memoryCacheList);
        // }
        // //清理缓存数据
        // else
        // {
        // Logger.i(TAG,
        // "GetChildCategories.memory.chache: return from memory fail, flush cache.");
        //
        // GlobalConfig.getInstance()
        // .getSubCategoryList()
        // .remove(String.valueOf(categoryId));
        // }
        // }
        // //当前目录对象是否缓存，用以处理二级目录为空的情况
        // else
        // {
        // CatelogModel model = GlobalConfig.getInstance()
        // .getCategoryMapping()
        // .get(String.valueOf(categoryId));
        //
        // if (null != model)
        // {
        // //当前缓存目录有效则说明该目录下无子目录列表(状态)
        // if (CacheUtil.getInstance().isCategoryModelHitCache(model))
        // {
        // return new ArrayList<CatelogModel>(0);
        // }
        // //清理缓存
        // else
        // {
        // GlobalConfig.getInstance()
        // .getCategoryMapping()
        // .remove(String.valueOf(categoryId));
        // }
        // }
        // }
        // }
        //
        // //允许本地栏目数据库缓存
        // boolean isEnableLocalDBCache = isLoadFromCache
        // && CacheUtil.getInstance().isEnableLocaleDBCache();
        //
        // if (isEnableLocalDBCache)
        // {
        // Logger.i(TAG,
        // "GetChildCategories.localdb.chache: Loading from locale db.");
        //
        // //内存缓存无数据本地数据读取(并刷新缓存)
        // //读取指定栏目下子目录列表
        // ArrayList<CatelogModel> localDBCacheList =
        // categoryService.queryCategoryListByParentCategoryID(String.valueOf(categoryId));
        //
        // //本地有缓存数据
        // if (null != localDBCacheList && !localDBCacheList.isEmpty())
        // {
        // Logger.i(TAG,
        // "GetChildCategories.localdb.chache: Loading from locale db, list: "
        // + localDBCacheList.size());
        //
        // //验证缓存数据有效性
        // boolean isCacheHit = CacheUtil.getInstance()
        // .isCategoryModelHitCache(localDBCacheList.get(0));
        // //缓存数据有效立即返回
        // if (isCacheHit)
        // {
        // Logger.i(TAG,
        // "GetChildCategories.localdb.chache: return from local success.");
        //
        // //刷新内存缓存(如果开启的话)
        // if (CacheUtil.getInstance().isEnableCategoryMemCache())
        // {
        // GlobalConfig.getInstance()
        // .getSubCategoryList()
        // .put(String.valueOf(categoryId),
        // localDBCacheList);
        // }
        //
        // //判定是否需要预加载刷新缓存
        // if (CacheUtil.getInstance()
        // .isNeedRefreshCache(localDBCacheList.get(0)))
        // {
        // //异步刷新缓存
        // flushGetChildCategories(categoryId);
        // }
        // return new
        // ArrayList<CatelogModel>(localDBCacheList);//缓存数据需要与UI数据隔离，防止两边修改(clear、remove)造成影响
        // }
        // //清理缓存
        // else
        // {
        // //清理本地失效缓存数据
        // int topCacheCount =
        // categoryService.deleteCategoryListByParentID(String.valueOf(categoryId));
        // Logger.i(TAG,
        // "GetChildCategories.localdb.chache:, Clear sub category list, size: "
        // + topCacheCount);
        // }
        // }
        // }

        // 上述缓存数据无效(无缓存数据或者缓存数据已失效)，调用服务端数据并更新本地缓存
        ArrayList<AllCatelogModel> listCatelogModel = null;

        JSONObject jsonData = requestHttpGetData(Constant.GETALLCHILDCATEGORIES_URL
                + categoryId + "/allchild");
        JSONArray jsonArray = jsonData
                .optJSONArray(ServerConstant.Catelog.CONSTANT_MODEL);
        if (jsonArray != null) {
            listCatelogModel = new ArrayList<AllCatelogModel>();
            for (int i = 0; i < jsonArray.length(); i++) {
                listCatelogModel.add(new AllCatelogModel()
                        .json2allCategories(jsonArray.optJSONObject(i)));
            }
        }

        return listCatelogModel;
    }

    @Override
    public ArrayList<CatelogModel> GetChildCategories(int categoryId)
            throws DxException {
        return GetChildCategories(categoryId, true);
    }

    /**
     * 获取目录的下一级目录列表 [参数说明]
     * <p>
     * 二级缓存方式读取，优先级如下：
     * <p>
     * 1、本地数据库读取 2、远程服务端读取
     * <p>
     * 注：缓存策略见{@link CacheUtil}
     *
     * @return categoryId [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @Override
    public ArrayList<CatelogModel> GetChildCategories(int categoryId,
                                                      boolean isLoadFromCache) throws DxException {
		/*
		 * //栏目内存缓存 if (isLoadFromCache &&
		 * CacheUtil.getInstance().isEnableCategoryMemCache()) { Logger.i(TAG,
		 * "GetChildCategories.memory.chache: Loading from memory.");
		 * 
		 * //获取内存缓存数据 ArrayList<CatelogModel> memoryCacheList =
		 * GlobalConfig.getInstance
		 * ().getSubCategoryList().get(String.valueOf(categoryId));
		 * 
		 * //缓存数据不为空 if (null != memoryCacheList && !memoryCacheList.isEmpty())
		 * { boolean isCacheHit =
		 * CacheUtil.getInstance().isCategoryModelHitCache
		 * (memoryCacheList.get(0));
		 * 
		 * Logger.i(TAG,
		 * "GetChildCategories.memory.chache: Loading from memory, return: " +
		 * memoryCacheList.size());
		 * 
		 * //缓存数据有效立即返回 if (isCacheHit) { Logger.i(TAG,
		 * "GetChildCategories.memory.chache: return from memory success.");
		 * 
		 * // 判定是否需要预加载刷新缓存 if
		 * (CacheUtil.getInstance().isNeedRefreshCache(memoryCacheList.get(0)))
		 * { //异步刷新缓存 flushGetChildCategories(categoryId); } return new
		 * ArrayList<CatelogModel>(memoryCacheList); } //清理缓存数据 else {
		 * Logger.i(TAG,
		 * "GetChildCategories.memory.chache: return from memory fail, flush cache."
		 * );
		 * 
		 * GlobalConfig.getInstance().getSubCategoryList().remove(String.valueOf(
		 * categoryId)); } } //当前目录对象是否缓存，用以处理二级目录为空的情况 else { CatelogModel
		 * model =
		 * GlobalConfig.getInstance().getCategoryMapping().get(String.valueOf
		 * (categoryId));
		 * 
		 * if (null != model) { //当前缓存目录有效则说明该目录下无子目录列表(状态) if
		 * (CacheUtil.getInstance().isCategoryModelHitCache(model)) { return new
		 * ArrayList<CatelogModel>(0); } //清理缓存 else {
		 * GlobalConfig.getInstance()
		 * .getCategoryMapping().remove(String.valueOf(categoryId)); } } } }
		 * 
		 * //允许本地栏目数据库缓存 boolean isEnableLocalDBCache = isLoadFromCache &&
		 * CacheUtil.getInstance().isEnableLocaleDBCache();
		 * 
		 * if (isEnableLocalDBCache) { Logger.i(TAG,
		 * "GetChildCategories.localdb.chache: Loading from locale db.");
		 * 
		 * //内存缓存无数据本地数据读取(并刷新缓存) //读取指定栏目下子目录列表 ArrayList<CatelogModel>
		 * localDBCacheList =
		 * categoryService.queryCategoryListByParentCategoryID
		 * (String.valueOf(categoryId));
		 * 
		 * //本地有缓存数据 if (null != localDBCacheList &&
		 * !localDBCacheList.isEmpty()) { Logger.i(TAG,
		 * "GetChildCategories.localdb.chache: Loading from locale db, list: " +
		 * localDBCacheList.size());
		 * 
		 * //验证缓存数据有效性 boolean isCacheHit =
		 * CacheUtil.getInstance().isCategoryModelHitCache
		 * (localDBCacheList.get(0)); //缓存数据有效立即返回 if (isCacheHit) {
		 * Logger.i(TAG,
		 * "GetChildCategories.localdb.chache: return from local success.");
		 * 
		 * //刷新内存缓存(如果开启的话) if
		 * (CacheUtil.getInstance().isEnableCategoryMemCache()) {
		 * GlobalConfig.getInstance() .getSubCategoryList()
		 * .put(String.valueOf(categoryId), localDBCacheList); }
		 * 
		 * //判定是否需要预加载刷新缓存 if
		 * (CacheUtil.getInstance().isNeedRefreshCache(localDBCacheList.get(0)))
		 * { //异步刷新缓存 flushGetChildCategories(categoryId); } return new
		 * ArrayList
		 * <CatelogModel>(localDBCacheList);//缓存数据需要与UI数据隔离，防止两边修改(clear
		 * 、remove)造成影响 } //清理缓存 else { //清理本地失效缓存数据 int topCacheCount =
		 * categoryService
		 * .deleteCategoryListByParentID(String.valueOf(categoryId));
		 * Logger.i(TAG,
		 * "GetChildCategories.localdb.chache:, Clear sub category list, size: "
		 * + topCacheCount); } } }
		 */

        Logger.d(TAG, "Enter into GetChildCategories, categoryId: "
                + categoryId);

        // 上述缓存数据无效(无缓存数据或者缓存数据已失效)，调用服务端数据并更新本地缓存
        ArrayList<CatelogModel> listCatelogModel = null;
        JSONObject jsonData = requestHttpGetData(Constant.GETCHILDCATEGORIES_URL
                + categoryId + "/child");
        JSONArray jsonArray = jsonData
                .optJSONArray(ServerConstant.Catelog.CONSTANT_MODEL);
        if (jsonArray != null) {
            listCatelogModel = new ArrayList<CatelogModel>();
            CatelogModel tmpModel = null;

            for (int i = 0; i < jsonArray.length(); i++) {
                tmpModel = CatelogModel.json2ChildCategories(jsonArray
                        .optJSONObject(i));
                tmpModel.setCacheUpdateTime(System.currentTimeMillis());// 刷新缓存时间
                // 刷新本地数据库缓存
                // if (isEnableLocalDBCache)
                // {
                // categoryService.saveCategoryInfo(tmpModel);// 保存到本地数据库里面
                // }
                tmpModel.setParentId(String.valueOf(categoryId));// 设置父栏目ID
                listCatelogModel.add(tmpModel);
            }
        }

        // 刷新内存缓存(如果开启的话)
		/*
		 * if (isLoadFromCache &&
		 * CacheUtil.getInstance().isEnableCategoryMemCache()) { if (null !=
		 * listCatelogModel && !listCatelogModel.isEmpty()) {
		 * GlobalConfig.getInstance() .getSubCategoryList()
		 * .put(String.valueOf(categoryId), new
		 * ArrayList<CatelogModel>(listCatelogModel));//使用新列表数据存储，防止UI
		 * 对列表Clear、remove操作 } //缓存数据状态: 当前目录下无子目录 else { CatelogModel model =
		 * new CatelogModel(); model.setId(categoryId);
		 * model.setCacheUpdateTime(System.currentTimeMillis());
		 * GlobalConfig.getInstance
		 * ().getCategoryMapping().put(String.valueOf(categoryId),
		 * model);//使用新列表数据存储，防止UI 对列表Clear、remove操作 } }
		 */

        return listCatelogModel;
    }

    /*
     * @param keyName
     *
     * @param currentEndIndex
     *
     * @param pageCount
     *
     * @param orderByField
     *
     * @param whereStr
     *
     * @return
     *
     * @see
     * com.weipu.common.facade.ProductServiceProvider#getSearchProductList(java
     * .lang.String, int, int, java.lang.String, java.lang.String)
     */
    @Override
    public SearchModel getSearchProductList(String keyName,
                                            int currentEndIndex, int pageCount, String orderByField,
                                            double startPrice, double endPrice, double beginStar,
                                            String currencyCode, long customerID, boolean isFilter, String categoryIds) throws DxException {
        SearchModel searchModel = new SearchModel();
        List<ProductModel> productModels = new ArrayList<ProductModel>();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;
        String Url = UrlUtils.getSearchProUrl(keyName, currentEndIndex, pageCount, orderByField, startPrice, endPrice, beginStar);
        JSONObject json_data = requestHttpGetData(Constant.GETSEARCHPRODUCTLIST_URL
                + "?keyName=" + keyName//StringUtil.strFilterOut(keyName)--不需要过滤了2016.6.15 Tony
                + "&CurrentEndIndex=" + currentEndIndex + "&pageCount="
                + pageCount + "&orderbyField=" + orderByField + "&whereStr="
                + whereStr + "&customerID=" + customerID + "&IsFilter=" + isFilter + "&categoryIds=" + categoryIds/*Url*/, currencyCode);
        searchModel.setTotalRecords(json_data
                .optInt(Constant.JSON_TOTALRECORDS));
        searchModel.setStartIndex(json_data.optInt(Constant.JSON_STARTINDEX));
        searchModel.setEndCurrentIndex(json_data
                .optInt(Constant.JSON_ENDCURRENTINDEX));
        searchModel
                .setCurrencyCode(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
        searchModel
                .setCurrencyCodeSymbol(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        JSONArray json_products = json_data
                .optJSONArray(Constant.JSON_PRODUCTS);
        for (int i = 0; i < json_products.length(); i++) {
            try {
                productModels.add(ProductModel.json2product(json_products
                        .getJSONObject(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        searchModel.setProductModels(productModels);

        return searchModel;
    }

    /*
     * @param keyName
     *
     * @param currentEndIndex
     *
     * @param pageCount
     *
     * @param orderByField
     *
     * @param whereStr
     *
     * @return
     *
     * @see
     * com.weipu.common.facade.ProductServiceProvider#getProductListUp(java.
     * lang.String, int, int, java.lang.String, java.lang.String)
     */
    @Override
    public SearchModel getProductListUp(String keyName, int currentEndIndex,
                                        int pageCount, String orderByField, double startPrice,
                                        double endPrice, double beginStar, String currencyCode)
            throws DxException {
        SearchModel searchModel = new SearchModel();
        List<ProductModel> productModels = new ArrayList<ProductModel>();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;
        JSONObject json = requestHttpGetAll(Constant.GETPRODUCTLISTUP_URL
                + "?keyName=" + StringUtil.strFilterOut(keyName)
                + "&CurrentEndIndex=" + currentEndIndex + "&pageCount="
                + pageCount + "&orderbyField=" + orderByField + "&whereStr="
                + whereStr, currencyCode);
        searchModel.setStartIndex(json.optInt(Constant.JSON_STARTINDEX));
        searchModel.setEndCurrentIndex(json
                .optInt(Constant.JSON_ENDCURRENTINDEX));
        JSONObject json_data = json.optJSONObject(Constant.JSON_DATA);
        searchModel
                .setCurrencyCode(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
        searchModel
                .setCurrencyCodeSymbol(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        JSONArray json_products = json_data
                .optJSONArray(Constant.JSON_PRODUCTS);
        for (int i = 0; i < json_products.length(); i++) {
            try {
                productModels.add(ProductModel.json2product(json_products
                        .getJSONObject(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        searchModel.setProductModels(productModels);
        Logger.e("---", json.toString());
        return searchModel;
    }

    /*
     * @param keyName
     *
     * @param currentEndIndex
     *
     * @param pageCount
     *
     * @param orderByField
     *
     * @param whereStr
     *
     * @return
     *
     * @see
     * com.weipu.common.facade.ProductServiceProvider#getProductList(java.lang
     * .String, int, int, java.lang.String, java.lang.String)
     */
    @Override
    public SearchModel getProductList(String keyName, int StartIndex,
                                      int pageCount, String orderByField, double startPrice,
                                      double endPrice, double beginStar, String currencyCode)
            throws DxException {
        SearchModel searchModel = new SearchModel();
        List<ProductModel> productModels = new ArrayList<ProductModel>();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;

        JSONObject json = requestHttpGetData(Constant.GETPRODUCTLIST_URL
                        + "?keyName=" + StringUtil.strFilterOut(keyName)
                        + "&StartIndex=" + StartIndex + "&pageCount=" + pageCount
                        + "&orderbyField=" + orderByField + "&whereStr=" + whereStr,
                currencyCode);
        searchModel.setStartIndex(json.optInt(Constant.JSON_STARTINDEX));
        searchModel.setEndCurrentIndex(json
                .optInt(Constant.JSON_ENDCURRENTINDEX));
        searchModel
                .setCurrencyCode(json
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
        searchModel
                .setCurrencyCodeSymbol(json
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        JSONObject json_data = json.optJSONObject(Constant.JSON_DATA);
        JSONArray json_products = json_data
                .optJSONArray(Constant.JSON_PRODUCTS);
        for (int i = 0; i < json_products.length(); i++) {
            try {
                productModels.add(ProductModel.json2product(json_products
                        .getJSONObject(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        searchModel.setProductModels(productModels);
        return searchModel;
    }

    /*
     * @param whereStr
     *
     * @param categoryId
     *
     * @param relatedType
     *
     * @return
     *
     * @see com.weipu.common.facade.ProductServiceProvider#
     * getProductResultByCategoryRelatedType(java.lang.String, java.lang.String,
     * java.lang.String)
     */
    @Override
    public ProductResultModel getProductResultByCategoryRelatedType(
            double startPrice, double endPrice, double beginStar,
            String categoryId, String relatedType) throws DxException {
        ProductResultModel productResultModel = new ProductResultModel();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;
        JSONObject json_data = requestHttpGetData(
                Constant.GETPRODUCTRESULTBYCATEGORYRELATEDTYPE_URL
                        + "?whereStr=" + whereStr + "&CategoryId=" + categoryId
                        + "&RelatedType=" + relatedType, null);
        JSONObject json_products = json_data
                .optJSONObject(Constant.JSON_PRODUCTS);
        productResultModel = ProductResultModel.json2product(json_products);
        return productResultModel;
    }

    /*
     * @param keyName
     *
     * @param whereStr
     *
     * @param categoryId
     *
     * @param relatedType
     *
     * @return
     *
     * @see
     * com.weipu.common.facade.ProductServiceProvider#getProductResult(java.
     * lang.String, java.lang.String, java.lang.String, java.lang.String)
     */
    @Override
    public ProductResultModel getProductResult(String keyName,
                                               double startPrice, double endPrice, double beginStar,
                                               String categoryId, String relatedType) throws DxException {
        ProductResultModel productResultModel = new ProductResultModel();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;
        JSONObject json_data = requestHttpGetData(Constant.GETPRODUCTRESULT_URL
                        + "?keyName=" + keyName + "&whereStr=" + whereStr
                        + "&CategoryId=" + categoryId + "&RelatedType=" + relatedType,
                null);
        JSONObject json_products = json_data
                .optJSONObject(Constant.JSON_PRODUCTS);
        productResultModel = ProductResultModel.json2product(json_products);

        return productResultModel;
    }

    /*
     * @param sku
     *
     * @param CICID
     *
     * @param userName
     *
     * @param pageIndex
     *
     * @param pageSize
     *
     * @return
     *
     * @throws DxException
     *
     * @see
     * com.weipu.common.facade.ProductServiceProvider#getCustomerPhotoList(int,
     * long, java.lang.String, int, int)
     */
    @Override
    public ArrayList<CustomerPhotosModel> getCustomerPhotoList(int sku,
                                                               long CICID, String userName, int pageIndex, int pageSize,
                                                               String token) throws DxException {
        ArrayList<CustomerPhotosModel> customerPhotosModels = null;

        JSONObject json_data = requestHttpGetData(Constant.CUSOTMERPHOTOLIST_URL
                + "?SKU=" + sku + "&Token=" + token + "&CICID=" + CICID
                + "&userName=" + userName + "&pageIndex=" + pageIndex
                + "&pageSize=" + pageSize);
        JSONArray json_resultset = json_data
                .optJSONArray(Constant.JSON_RESULTSET);
        customerPhotosModels = CustomerPhotosModel
                .jsonArray2customer(json_resultset);

        return customerPhotosModels;
    }

    /*
     * 获取商品详情信息。
     *
     * @param sku
     *
     * @return
     *
     * @see com.weipu.common.facade.ProductServiceProvider#getProductDetail(int)
     */
    @Override
    public ProductModel getProductDetail(int sku, String currencyCode)
            throws DxException {
        ProductModel productModel = null;
        JSONObject json_data = requestHttpGetData(Constant.GETPRODUCTDETAIL_URL
                + "?SKU=" + sku, currencyCode);
        JSONObject json_model = null;
        if (null != json_data) {
            if (Constant.BFD_DEBUGMODEL) {
                Log.d(TAG, json_data.toString());

            }
            json_model = json_data.optJSONObject(Constant.JSON_MODEL);
            productModel = ProductModel.json2product(json_model);
            productModel
                    .setCurrencyCode(json_data
                            .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
            productModel
                    .setCurrencyCodeSymbol(json_data
                            .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        }

        return productModel;
    }

    @Override
    public ArrayList<ReviewlistModel> getCusotmerReviewList(int sku,
                                                            String CICID, String username, int pageindex, int pagesize,
                                                            String token) throws DxException {
        String result = null;
        ArrayList<ReviewlistModel> reviewlistModels = new ArrayList<ReviewlistModel>();
        JSONObject json_data = requestHttpGetData(Constant.CUSOTMERREVIEWLIST_URL
                + "?SKU=" + sku + "&Token=" + token + "&CICID=" + CICID
                + "&userName=" + username + "&pageIndex=" + pageindex
                + "&pageSize=" + pagesize);
        JSONArray json_resultset = json_data
                .optJSONArray(Constant.JSON_RESULTSET);
        reviewlistModels = ReviewlistModel.jsonarray2product(json_resultset);

        return reviewlistModels;
    }

    // 1、数据异步刷新：异步请求服务端数据，数据返回后讲刷新到本地数据库缓存
    // 2、UI可以通过BaseServiceTask.setNeedBroadcast2UI指定是否接收实时数据返回(广播)
    private void flushProductListByCategoryIdAndRelatedType(int startindex,
                                                            int pageCount, String orderByField, double startPrice,
                                                            double endPrice, double beginStar, String relatedType) {
        BaseServiceTask<ArrayList<ProductModel>> task = new GetProductListByCategoryIdAndRelatedTypeTask(
                startindex, pageCount, orderByField, startPrice, endPrice,
                beginStar, relatedType, false);

        TaskExecutor.doTaskInBackground(task);
    }

    // 1、数据异步刷新：异步请求服务端数据，数据返回后讲刷新到本地数据库缓存
    // 2、UI可以通过BaseServiceTask.setNeedBroadcast2UI指定是否接收实时数据返回(广播)
    private void flushGetChildCategories(int categoryId) {
        BaseServiceTask<ArrayList<CatelogModel>> task = new GetChildCategoriesTask(
                categoryId, false);

        TaskExecutor.doTaskInBackground(task);
    }

    @Override
    public ArrayList<ProductModel> getProductListByCategoryIdAndRelatedType(
            int startindex, int pageCount, String orderByField,
            double startPrice, double endPrice, double beginStar,
            String relatedType, boolean isLoadFromCache) throws DxException {

        Logger.d(TAG,
                "Enter into getProductListByCategoryIdAndRelatedType, relatedType: "
                        + relatedType);

        // 允许内存缓存
        if (isLoadFromCache
                && CacheUtil.getInstance().isEnableProductMemCache()) {
            ArrayList<ProductModel> result = GlobalConfig.getInstance()
                    .getTopProductCache().get(relatedType);

            if (null != result && !result.isEmpty()) {
                Logger.i(
                        TAG,
                        "getProductListByCategoryIdAndRelatedType.memory.chache: load from memory, product list, size: "
                                + result.size());
                // 缓存有效
                if (CacheUtil.getInstance().isProductHitCache(result.get(0),
                        relatedType)) {
                    // 判定是否需要预加载刷新缓存
                    if (CacheUtil.getInstance().isNeedRefreshCache(
                            result.get(0))) {
                        // 异步刷新缓存
                        flushProductListByCategoryIdAndRelatedType(startindex,
                                pageCount, orderByField, startPrice, endPrice,
                                beginStar, relatedType);
                    }

                    Logger.i(
                            TAG,
                            "getProductListByCategoryIdAndRelatedType.memory.chache: load from memory success. ");
                    return result;
                }
                // 缓存失效
                else {
                    Logger.i(
                            TAG,
                            "getProductListByCategoryIdAndRelatedType.memory.chache: load from memory fail, clear up.");
                    GlobalConfig.getInstance().getTopProductCache()
                            .remove(relatedType);
                }
            }
        }

        // 是否允许本地数据库缓存
        boolean isEnableLocalDBCache = isLoadFromCache
                && CacheUtil.getInstance().isEnableLocaleDBCache();

        if (isEnableLocalDBCache) {
            Logger.i(
                    TAG,
                    "getProductListByCategoryIdAndRelatedType.localedb.chache:  loading from local. ");

            // 内存缓存无数据本地数据读取(并刷新缓存)
            // 读取指定栏目下子目录列表
            ArrayList<ProductModel> localDBCacheList = productService
                    .queryProductListByType(relatedType);

            // 本地有缓存数据
            if (null != localDBCacheList && !localDBCacheList.isEmpty()) {
                Logger.i(
                        TAG,
                        "getProductListByCategoryIdAndRelatedType.localedb.chache: loading from local, size: "
                                + localDBCacheList.size());

                // 验证缓存数据有效性
                boolean isCacheHit = CacheUtil.getInstance().isProductHitCache(
                        localDBCacheList.get(0), relatedType);

                // 缓存数据有效立即返回
                if (isCacheHit) {
                    Logger.i(
                            TAG,
                            "getProductListByCategoryIdAndRelatedType.localedb.chache: loading from local success.");

                    // 刷新内存缓存(如果开启的话)
                    if (CacheUtil.getInstance().isEnableProductMemCache()) {
                        GlobalConfig.getInstance().getTopProductCache()
                                .put(relatedType, localDBCacheList);
                    }

                    // 判定是否需要预加载刷新缓存
                    if (CacheUtil.getInstance().isNeedRefreshCache(
                            localDBCacheList.get(0))) {
                        // 异步刷新缓存
                        flushProductListByCategoryIdAndRelatedType(startindex,
                                pageCount, orderByField, startPrice, endPrice,
                                beginStar, relatedType);
                    }

                    return new ArrayList<ProductModel>(localDBCacheList);// 缓存数据需要与UI数据隔离，防止两边修改(clear、remove)造成影响
                }
                // 清理缓存
                else {
                    // 清理本地失效缓存数据
                    int topCacheCount = productService
                            .deleteProductListByType(relatedType);
                    Logger.i(
                            TAG,
                            "getProductListByCategoryIdAndRelatedType.localedb.chache: Clear sub product list, size: "
                                    + topCacheCount);
                }
            }
        }

        ArrayList<ProductModel> productModels = new ArrayList<ProductModel>();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;

        JSONObject json_data = requestHttpGetData(
                Constant.GETPRODUCTLISTBYCATEGORYIDANDRELATEDTYPE_URL
                        + "?StartIndex=" + startindex + "&pageCount="
                        + pageCount + "&orderbyField=" + orderByField
                        + "&whereStr=" + whereStr + "&CategoryId="
                        + "&RelatedType=" + relatedType, null);
        JSONArray json_products = json_data
                .optJSONArray(Constant.JSON_PRODUCTS);

        ProductModel tmpModel = null;

        for (int i = 0; i < json_products.length(); i++) {
            try {
                tmpModel = ProductModel.json2product(json_products
                        .getJSONObject(i));
                tmpModel.setCacheUpdateTime(System.currentTimeMillis());// 刷新缓存时间

                productModels.add(tmpModel);

                // 本地数据库缓存
                if (isEnableLocalDBCache) {
                    productService.saveProductInfo(tmpModel, relatedType);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // 允许内存缓存
        if (isLoadFromCache
                && CacheUtil.getInstance().isEnableProductMemCache()
                && null != productModels && !productModels.isEmpty()) {
            GlobalConfig
                    .getInstance()
                    .getTopProductCache()
                    .put(relatedType,
                            new ArrayList<ProductModel>(productModels)); // 使用新列表数据存储，防止UI
            // 对列表Clear、remove操作
        }

        return productModels;
    }

    @Override
    public ArrayList<ProductModel> getProductListByCategoryIdAndRelatedType(
            int startindex, int pageCount, String orderByField,
            double startPrice, double endPrice, double beginStar,
            String relatedType) throws DxException {
        // 实时读取，处理分页请求(从服务端加载数据)
        return getProductListByCategoryIdAndRelatedType(startindex, pageCount,
                orderByField, startPrice, endPrice, beginStar, relatedType,
                false);
    }

    @Override
    public SearchModel getProductListByCategoryId(int startIndex,
                                                  int pageCount, String orderByField, double startPrice,
                                                  double endPrice, double beginStar, int categoryId,
                                                  String currencyCode) throws DxException {
        SearchModel searchModel = new SearchModel();
        List<ProductModel> productModels = new ArrayList<ProductModel>();
        String whereStr = "p>=" + startPrice + "," + "p<=" + endPrice + ","
                + "s>=" + beginStar;
        JSONObject json_data = requestHttpGetData(
                Constant.GETPRODUCTLISTBYCATEGORYID_URL + "?keyName="
                        + "&StartIndex=" + startIndex + "&pageCount="
                        + pageCount + "&orderbyField=" + orderByField
                        + "&whereStr=" + whereStr + "&customerID=0&isFilter=true&categoryIds=" + categoryId,
                currencyCode);
        searchModel
                .setCurrencyCode(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
        searchModel
                .setCurrencyCodeSymbol(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        JSONArray json_products = json_data
                .optJSONArray(Constant.JSON_PRODUCTS);
        for (int i = 0; i < json_products.length(); i++) {
            try {
                productModels.add(ProductModel.json2product(json_products
                        .getJSONObject(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        searchModel.setProductModels(productModels);

        return searchModel;
    }

    /*
     * 查询库存量
     *
     * @param sku
     *
     * @return
     *
     * @throws DxException
     *
     * @see com.weipu.common.facade.ProductServiceProvider#getSaleslimit(int[])
     */
    @Override
    public Map<Integer, SalesLimitModel> getSaleslimit(
            ArrayList<Integer> skuList) throws DxException {
        Map<Integer, SalesLimitModel> saleslimitMap = null;
        Logger.i("postOrPutWebInterface", "getSaleslimit");
        JSONObject jsonData = requestHttpPostData(mapUrl.get(ServerConstant.RequestMethodNameConstant.METHOD_SALESLIMIT), skuList);
        JSONArray salesModel = jsonData.optJSONArray("Model");
        if (null != salesModel && salesModel.length() > 0) {
            saleslimitMap = new HashMap<Integer, SalesLimitModel>();
            SalesLimitModel salesLimitModel = null;
            try {
                for (int i = 0; i < skuList.size(); i++) {
                    salesLimitModel = SalesLimitModel
                            .salesLimitModel2json(salesModel.getJSONObject(i));
                    saleslimitMap
                            .put(salesLimitModel.getSku(), salesLimitModel);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return saleslimitMap;
    }

    /**
     * 首页四个按钮统一数据请求接口
     */
    @Override
    public SearchModel getHomeBtnDataList(long customerID, boolean isFilter,
                                          String categoryIds, int pageindex, int pagesize, String type,
                                          String orderByField) throws DxException {
        String result = null;
        ArrayList<ProductModel> productModels = null;
        // getAuthenticationAndsetHeadAndmessage(type);
        // ResponseEntity<String> responseEntity;
        SearchModel searchModel = new SearchModel();

        String requestKey = "";
        if (Constant.TYPE_TOPSELLERS.equals(type)) {
            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_TOPSELLERS;
        } else if (Constant.TYPE_NEWARRIVALS.equals(type)) {
            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_NEWARRIVALS;
        } else if (Constant.TYPE_MVP24HRS.equals(type)) {
            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_MVPRODUCTS;
        } else if (Constant.TYPE_LATESTDISCOUNT.equals(type)) {
            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_LATESTDISCOUNTS;
        } else if (Constant.TYPE_SPORTLIGHTS.equals(type)) {
            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_SPOTLIGHTS;
        } else {
//            requestKey = ServerConstant.RequestMethodNameConstant.METHOD_USWAREHOUSE;
            requestKey = "";
        }

        String url ;
        if (TextUtils.isEmpty(requestKey)) {
            //如果是新增的功能,则使用接口返回的后缀地址
            url = Constant.BASE_URL + StringUtil.getConfig(Constant.JSON_INTERFACESUFFIX,
                    Constant.USWAREHOUSE_URL);
        }else {
            url = mapUrl.get(requestKey);
        }

        String Url = url + "?CustomerID=" + customerID + "&IsFilter=" + isFilter + "&CategoryIds=" + categoryIds + "&pageSize="
                + pagesize + "&pageIndex=" + pageindex + "&orderbyField=" + orderByField;
//		String Url = UrlUtils.getHomeBtnUrl(pageindex, pagesize, type, orderByField);
        String currencyCode = StringUtil.getConfig(
                ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, "USD");
        JSONObject json = requestHttpGetAll(Url, currencyCode);
        Logger.d(TAG + "_getHomeBtnDataList", "hhh " + json.toString());
        productModels = getPublicList(json, type, pageindex);
        Logger.d(TAG + "_getHomeBtnDataList", "aaa " + productModels.toString());
        JSONObject json_data = json.optJSONObject(Constant.JSON_DATA);
        searchModel.setProductModels(productModels);
        searchModel
                .setCurrencyCode(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE));
        searchModel
                .setCurrencyCodeSymbol(json_data
                        .optString(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE_SYMBOL));
        // 内存缓存
        if (pageindex == Constant.HOME_CACHE_PAGEINDEX
                && CacheUtil.getInstance().isEnableProductMemCache()
                && null != productModels && !productModels.isEmpty()) {
            GlobalConfig.getInstance().getTopProductCache()
                    .put(type, new ArrayList<ProductModel>(productModels)); // 使用新列表数据存储，防止UI
            // 对列表Clear、remove操作
        }
        return searchModel;
    }

	/* *//**
     * 首页新增TopSellers
     */
	/*
	 * @Override public ArrayList<ProductModel> getTopSellersList(int pageindex,
	 * int pagesize) throws DxException { String result = null;
	 * ArrayList<ProductModel> topSellersModels = null;
	 * getAuthenticationAndsetHeadAndmessage(Constant.TYPE_TOPSELLERS);
	 * ResponseEntity<String> responseEntity;
	 * 
	 * try { Logger.i("getTopSellersList", "star"); responseEntity =
	 * restTemplate
	 * .exchange(mapUrl.get(ServerConstant.RequestMethodNameConstant.
	 * METHOD_TOPSELLERS) + "?categoryId=0" + "&pageSize=" + pagesize +
	 * "&pageIndex=" + pageindex,
	 * mapMethod.get(ServerConstant.RequestMethodNameConstant
	 * .METHOD_TOPSELLERS), requestEntity, String.class); //获取服务器反悔的Etag标志
	 * String eTag=responseEntity.getHeaders().getETag();
	 * Logger.i(TAG+"_getTopSellersList", "getTopSellersList Etag: "+eTag
	 * +" Status: "+responseEntity.getStatusCode());
	 * if(null!=eTag&&!eTag.isEmpty()){ StringUtil.saveConfig("TopSellers_ETag",
	 * eTag); } String statusCode=responseEntity.getStatusCode().toString();
	 * //304代表数据没有改变 if("304".equals(statusCode)){
	 * Logger.i(TAG+"_getTopSellersList",
	 * "getTopSellersList status is 304 get Cache data");
	 * topSellersModels=getHomeFourProductTypeCache(Constant.TYPE_TOPSELLERS);
	 * }else{ //TODO 删除本地缓存 返回码不为304代表缓存失效
	 * if("200".equals(statusCode)&&pageindex==Constant.HOME_CACHE_PAGEINDEX){
	 * Logger.i(TAG+"_getTopSellersList",
	 * "getTopSellersList status is 200 Cache data is Useless to Clear");
	 * GlobalConfig
	 * .getInstance().getTopProductCache().remove(Constant.TYPE_TOPSELLERS);
	 * productService.deleteProductListByType(Constant.TYPE_TOPSELLERS); }
	 * result = responseEntity.getBody().toString(); JSONObject json =
	 * returnResult(result); topSellersModels =
	 * getPublicList(json,Constant.TYPE_TOPSELLERS,pageindex); //内存缓存 if
	 * (pageindex==Constant.HOME_CACHE_PAGEINDEX&&CacheUtil.getInstance().
	 * isEnableProductMemCache() && null != topSellersModels &&
	 * !topSellersModels.isEmpty()) { GlobalConfig.getInstance()
	 * .getTopProductCache() .put(Constant.TYPE_TOPSELLERS, new
	 * ArrayList<ProductModel>(topSellersModels)); //使用新列表数据存储，防止UI
	 * 对列表Clear、remove操作 } Logger.d(TAG+"_getTopSellersList",
	 * "getTopSellersList result: "+json.toString()); } } catch
	 * (ResourceAccessException e) { Logger.e(e.getMessage(), e); // 链接超时 if
	 * (e.getCause() instanceof SocketTimeoutException||e.getCause() instanceof
	 * ConnectTimeoutException) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT); } else
	 * if(e.getCause() instanceof UnknownHostException){ throw new
	 * DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE); } else {
	 * if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){ throw
	 * new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
	 * }else{ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR); } } }
	 * catch (HttpClientErrorException e) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
	 * }catch(HttpServerErrorException e){ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR); }
	 * 
	 * return topSellersModels; }
	 *//**
     * 首页新增MvProducts
     */
	/*
	 * @Override public ArrayList<ProductModel> getMvProductsList(int pageindex,
	 * int pagesize) throws DxException { String result = null;
	 * ArrayList<ProductModel> mvProductsModels = null;
	 * getAuthenticationAndsetHeadAndmessage(Constant.TYPE_MVP24HRS);
	 * ResponseEntity<String> responseEntity;
	 * 
	 * try { Logger.i("getMvProductsList", "star"); responseEntity =
	 * restTemplate
	 * .exchange(mapUrl.get(ServerConstant.RequestMethodNameConstant.
	 * METHOD_MVPRODUCTS) + "?categoryId=0" + "&pageSize=" + pagesize +
	 * "&pageIndex=" + pageindex,
	 * mapMethod.get(ServerConstant.RequestMethodNameConstant
	 * .METHOD_MVPRODUCTS), requestEntity, String.class); String
	 * ETag=responseEntity.getHeaders().getETag(); Logger.i("getMvProductsList",
	 * "end "+responseEntity.getStatusCode()); result =
	 * responseEntity.getBody().toString(); Logger.i(TAG,
	 * "getMvProductsList result: "+result); JSONObject json =
	 * returnResult(result); mvProductsModels =
	 * getPublicList(json,Constant.TYPE_MVP24HRS,pageindex); } catch
	 * (ResourceAccessException e) { Logger.e(e.getMessage(), e); // 链接超时 if
	 * (e.getCause() instanceof SocketTimeoutException||e.getCause() instanceof
	 * ConnectTimeoutException) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT); } else
	 * if(e.getCause() instanceof UnknownHostException){ throw new
	 * DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE); } else {
	 * if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){ throw
	 * new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
	 * }else{ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR); } } }
	 * catch (HttpClientErrorException e) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
	 * }catch(HttpServerErrorException e){ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR); } return
	 * mvProductsModels; }
	 *//**
     * 首页新增NewArrivals
     */
	/*
	 * @Override public ArrayList<ProductModel> getNewArrivalsList(int
	 * pageindex, int pagesize) throws DxException { String result = null;
	 * ArrayList<ProductModel> newArrivalsModels = null;
	 * getAuthenticationAndsetHeadAndmessage(Constant.TYPE_NEWARRIVALS);
	 * ResponseEntity<String> responseEntity;
	 * 
	 * try { Logger.i("getNewArrivalsList", "star"); responseEntity =
	 * restTemplate
	 * .exchange(mapUrl.get(ServerConstant.RequestMethodNameConstant.
	 * METHOD_NEWARRIVALS) + "?categoryId=0" + "&pageSize=" + pagesize +
	 * "&pageIndex=" + pageindex,
	 * mapMethod.get(ServerConstant.RequestMethodNameConstant
	 * .METHOD_NEWARRIVALS), requestEntity, String.class);
	 * Logger.i("getNewArrivalsList", "end"); result =
	 * responseEntity.getBody().toString(); Logger.i("getNewArrivalsList",
	 * "result "+result); JSONObject json = returnResult(result);
	 * newArrivalsModels =
	 * getPublicList(json,Constant.TYPE_NEWARRIVALS,pageindex);
	 * Logger.i("getNewArrivalsList",
	 * "newArrivalsModels size"+newArrivalsModels.size()); } catch
	 * (ResourceAccessException e) { Logger.e(e.getMessage(), e); // 链接超时 if
	 * (e.getCause() instanceof SocketTimeoutException||e.getCause() instanceof
	 * ConnectTimeoutException) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT); } else
	 * if(e.getCause() instanceof UnknownHostException){ throw new
	 * DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE); } else {
	 * if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){ throw
	 * new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
	 * }else{ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR); } } }
	 * catch (HttpClientErrorException e) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
	 * }catch(HttpServerErrorException e){ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR); } return
	 * newArrivalsModels; }
	 *//**
     * 首页新增LatestDiscounts
     */
	/*
	 * @Override public ArrayList<ProductModel> getLatestDiscountsList(int
	 * pageindex, int pagesize) throws DxException { String result = null;
	 * ArrayList<ProductModel> latestDiscountsModels = null;
	 * getAuthenticationAndsetHeadAndmessage(Constant.TYPE_LATESTDISCOUNT);
	 * ResponseEntity<String> responseEntity;
	 * 
	 * try { Logger.i("getLatestDiscountsList", "star"); responseEntity =
	 * restTemplate
	 * .exchange(mapUrl.get(ServerConstant.RequestMethodNameConstant.
	 * METHOD_LATESTDISCOUNTS) + "?categoryId=0" + "&pageSize=" + pagesize +
	 * "&pageIndex=" + pageindex,
	 * mapMethod.get(ServerConstant.RequestMethodNameConstant
	 * .METHOD_LATESTDISCOUNTS), requestEntity, String.class);
	 * Logger.i("getLatestDiscountsList", "end"); result =
	 * responseEntity.getBody().toString(); JSONObject json =
	 * returnResult(result); latestDiscountsModels =
	 * getPublicList(json,Constant.TYPE_LATESTDISCOUNT,pageindex); } catch
	 * (ResourceAccessException e) { Logger.e(e.getMessage(), e); // 链接超时 if
	 * (e.getCause() instanceof SocketTimeoutException||e.getCause() instanceof
	 * ConnectTimeoutException) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT); } else
	 * if(e.getCause() instanceof UnknownHostException){ throw new
	 * DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE); } else {
	 * if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){ throw
	 * new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
	 * }else{ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR); } } }
	 * catch (HttpClientErrorException e) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
	 * }catch(HttpServerErrorException e){ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR); } return
	 * latestDiscountsModels; }
	 *//**
     * 首页新增Spotlights
     */
	/*
	 * @Override public ArrayList<ProductModel> getSpotlights(int pageindex, int
	 * pagesize) throws DxException { String result = null;
	 * ArrayList<ProductModel> spotlightsModels = null;
	 * getAuthenticationAndsetHeadAndmessage(Constant.TYPE_SPORTLIGHTS);
	 * ResponseEntity<String> responseEntity; try { Logger.i("getSpotlights",
	 * "star"); responseEntity =
	 * restTemplate.exchange(mapUrl.get(ServerConstant.
	 * RequestMethodNameConstant.METHOD_SPOTLIGHTS) + "?pageSize=" + pagesize +
	 * "&pageIndex=" + pageindex,
	 * mapMethod.get(ServerConstant.RequestMethodNameConstant
	 * .METHOD_SPOTLIGHTS), requestEntity, String.class);
	 * Logger.i("getSpotlights", "end"); result =
	 * responseEntity.getBody().toString(); JSONObject json =
	 * returnResult(result); spotlightsModels =
	 * getPublicList(json,Constant.TYPE_SPORTLIGHTS,pageindex); } catch
	 * (ResourceAccessException e) { Logger.e(TAG,
	 * "Pro "+e.toString()+"Cause() "+e.getCause()); Logger.e(e.getMessage(),
	 * e); // 链接超时 if (e.getCause() instanceof
	 * SocketTimeoutException||e.getCause() instanceof ConnectTimeoutException)
	 * { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_CONNECT_TIMEOUT); } else
	 * if(e.getCause() instanceof UnknownHostException){ throw new
	 * DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE); } else {
	 * if(!NetWorkUtil.isNetworkAvailable(DXApplication.getContext())){ throw
	 * new DxException(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE);
	 * }else{ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR); } } }
	 * catch (HttpClientErrorException e) { throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_UNKONW_ERROR);
	 * }catch(HttpServerErrorException e){ throw new
	 * DxException(ServerConstant.ReturnCode.VALIDATOR_SERVER_ERROR); }
	 * 
	 * return spotlightsModels; }
	 */

    /**
     * 首页新增获取商品列表
     *
     * @param json
     * @param Type
     * @param pageindex
     * @return
     */
    public ArrayList<ProductModel> getPublicList(JSONObject json, String Type,
                                                 int pageindex) {
        ArrayList<ProductModel> productModels = new ArrayList<ProductModel>();
        JSONObject json_data = json.optJSONObject(Constant.JSON_DATA);
        JSONArray json_products = json_data.optJSONArray(Constant.JSON_OBJ);
        ProductModel tmpModel = null;
        for (int i = 0; i < json_products.length(); i++) {
            try {
                tmpModel = ProductModel.json3product(json_products
                        .getJSONObject(i));
                if (pageindex == Constant.HOME_CACHE_PAGEINDEX) {
                    // 缓存到数据库
                    productService.saveProductInfo(tmpModel, Type);
                }
                productModels.add(tmpModel);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Logger.d("---", json.toString());
        return productModels;
    }

    /**
     * 首页四个Button获取缓存数据 ，该数据只对第一页及PageIndex=1（第一页）做数据做缓存
     *
     * @param Type 首页btn 类型 由于该缓存功能与服务器配合 缓存失效时间依照网络请求的 反回嘛 如果不是304代表数据失效
     * @return
     */
    private ArrayList<ProductModel> getHomeFourProductTypeCache(String Type) {
        if (/* isLoadFromCache && */CacheUtil.getInstance()
                .isEnableProductMemCache()) {
            ArrayList<ProductModel> result = GlobalConfig.getInstance()
                    .getTopProductCache().get(Type);

            if (null != result && !result.isEmpty()) {
                return result;
            }
        }

        Logger.i(TAG,
                "getTopProductCache() localedb chache:  loading from local. ");

        // 内存缓存无数据本地数据读取(并刷新缓存)
        // 读取指定栏目下子目录列表
        ArrayList<ProductModel> localDBCacheList = productService
                .queryProductListByType(Type);

        // 本地有缓存数据
        if (null != localDBCacheList && !localDBCacheList.isEmpty()) {
            Logger.i(
                    TAG,
                    "getProductListByCategoryIdAndRelatedType.localedb.chache: loading from local, size: "
                            + localDBCacheList.size());

            // 刷新内存缓存(如果开启的话)
            if (CacheUtil.getInstance().isEnableProductMemCache()) {
                GlobalConfig.getInstance().getTopProductCache()
                        .put(Type, localDBCacheList);
            }
            return new ArrayList<ProductModel>(localDBCacheList);// 缓存数据需要与UI数据隔离，防止两边修改(clear、remove)造成影响
        }
        return null;
    }


    @Override
    public ArrayList<ProductModel> getActiveProduct(int activeType,
                                                    String activeID, int startIndex, int pageSize, String orderbyField,
                                                    long customerID, boolean isFilter, String categoryIds)
            throws DxException {
        JSONObject jsonObject = requestHttpGetData(Constant.GETACTIVEPRODUCT_URL + "?getType=" + activeType + "&dataID=" + activeID + "&startIndex=" + startIndex
                + "&pageSize=" + pageSize + "&orderbyField=" + orderbyField + "&customerID=" + customerID + "&isFilter=" + isFilter + "&categoryIds=" + categoryIds, StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, "USD"));
        JSONArray jsonArray = jsonObject.optJSONArray("Obj");
        ArrayList<ProductModel> list = ProductModel.jsonArray2Products(jsonArray);
        if (null != list && list.size() > 0) {
            list.get(0).setCurrencyCodeSymbol(jsonObject.optString("CurrencyCodeSymbol"));
        }
        return list;
    }

}
